/******************************************************************************
 *
 * Project:		mGameEngine
 * File:		thread.cpp
 * Author:		karooolek
 * Created on:	2009-01-06
 *
 ******************************************************************************/

#include "thread.h"


#ifdef WIN32
DWORD WINAPI Thread::_threadEntry(LPVOID thread)
{
	static_cast<Thread *>(thread)->_run();
	return 0;
}
#else
void *Thread::_threadEntry(void *thread)
{
	static_cast<Thread *>(thread)->_run();
	pthread_exit(NULL);
}
#endif

Thread::Thread() :
	_stop(false)
{
}

Thread::~Thread()
{
#ifdef WIN32
	CloseHandle(_thread);
#else
#endif
}

void Thread::start()
{
#ifdef WIN32
	_thread = CreateThread((_SECURITY_ATTRIBUTES *)NULL, 0, _threadEntry, this, 0, NULL);
#else
	pthread_create(&_thread, NULL, _threadEntry, this);
#endif
}

void Thread::exec()
{
	_run();
}

void Thread::stop() // hammertime!
{
	_stop = true;
}

void Thread::terminate()
{
#ifdef WIN32
	TerminateThread(_thread, 0);
#else
	pthread_cancel(_thread);
#endif
}

void Thread::_sleep(float sec)
{
#ifdef WIN32
	Sleep(1000 * sec);
#else
	sleep(uint(sec));
#endif
}

void Thread::resume()
{
#ifdef WIN32
	ResumeThread(_thread);
#else
	pthread_mutex_unlock(&_suspended);
#endif
}

void Thread::suspend()
{
#ifdef WIN32
	SuspendThread(_thread);
#else
	pthread_mutex_lock(&_suspended);
#endif
}

void Thread::join() const
{
#ifdef _WIN32
	WaitForSingleObject(_thread, INFINITE);
#else
	pthread_join(_thread, NULL);
#endif
}
